package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.RolePers;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RolePersMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.service.RoleService;
import cn.kgc.vue.mapper.RoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mengshun
 * @description 针对表【sys_role】的数据库操作Service实现
 * @createDate 2023-12-07 09:12:11
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    @Resource
    private UserRoleMapper userRoleMapper;
    
    @Resource
    private RolePersMapper rolePersMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult roleList(QueryCondition<Role> queryCondition) {

        Page<Role> rolePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        Role query = queryCondition.getQuery();

        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        // roleName  roleEn
        lambda.eq(StringUtils.isNotEmpty(query.getRoleCh()), Role::getRoleCh, query.getRoleCh())
                .eq(StringUtils.isNotEmpty(query.getRoleEn()), Role::getRoleEn, query.getRoleEn())
                .orderByDesc(Role::getCreateTime);


        baseMapper.selectPage(rolePage, lambda);

        HashMap<String, Object> result = new HashMap<>();
        result.put("total",rolePage.getTotal());
        result.put("pageData",rolePage.getRecords());

        return ResponseResult.success().data(result);
    }

    @Override
    public ResponseResult removeRoleById(Integer rid) {

        //  1.判定角色是否被占用 user_role
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,rid);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (userRoles.size()!=0){
            return  ResponseResult.fail().message("角色被占用,不能删除");
        }
        //  2.删除角色
        baseMapper.deleteById(rid);
        
        // 3. 删除角色和权限的关联数据   role_permission
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getRoleId,rid);
        rolePersMapper.delete(lambda1);

        return ResponseResult.success().message("删除成功");
    }

    @Override
    public ResponseResult getPermissionsByRoleId(Integer rid) {

        // 1.根据角色id  查询权限id
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,rid);
        List<Integer> pIds = rolePersMapper.selectList(lambda).stream().map(rp -> rp.getPerId()).collect(Collectors.toList());

        // 2. 根据权限id 查询权限表 获取所有按钮级别权限
        List<Integer> collect = new ArrayList<>();

        if (pIds.size()>0){
            collect  = permissionMapper.selectBatchIds(pIds).stream()
                    .filter(p -> p.getIsMenu() == 2)
                    .map(p -> p.getId()).collect(Collectors.toList());
        }

        return ResponseResult.success().data(collect);
    }

    @Override
    public ResponseResult addPermissionsByRoleId(Map<String, Object> permissions) {

        //{roleId=7, ids=[1, 2, 3, 4, 5, 6]}
        Integer roleId = (Integer) permissions.get("roleId");
        List<Integer> pIds = (List<Integer>) permissions.get("ids");

        // 1. 删除角色原有的权限  role_permission
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,roleId);
        rolePersMapper.delete(lambda);

        // 2.将角色新的权限信息添加到role_permission
        pIds.forEach(pid->{
            RolePers rolePers = new RolePers();
            rolePers.setRoleId(roleId);
            rolePers.setPerId(pid);
            rolePersMapper.insert(rolePers);
        });


        return ResponseResult.success().message("权限分配完成");
    }
}




